package cn.itcast.order.service;

import cn.itcast.order.client.UserClient;
import cn.itcast.order.mapper.OrderMapper;
import cn.itcast.order.pojo.Order;
import cn.itcast.order.pojo.User;
import com.alibaba.fastjson.JSON;
import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
//@DefaultProperties(defaultFallback="allMethodFallback")
public class OrderService {

    @Autowired
    private OrderMapper orderMapper;

//    @Autowired
//    private RestTemplate restTemplate;

    @Autowired
    private UserClient userClient;

    //@HystrixCommand
    public String queryOrderById(Long orderId) {
        // 1.查询订单
        Order order = orderMapper.findById(orderId);
        // 2.远程调用用户微服务http://localhost:8081/user/1  返回User对象
        //User user = restTemplate.getForObject("http://localhost:8081/user/"+order.getUserId(), User.class);
        //User user = restTemplate.getForObject("http://userservice/user/"+order.getUserId(), User.class);
        User user = userClient.findById(order.getUserId());
        //3.把用户user对象set到Order对象中
        order.setUser(user);
        // 4.返回
        return JSON.toJSONString(order);
    }

    //当前降级方法要和原方法参数和返回类型保持一致
    public String queryOrderByIdFallback(Long orderId){

        return "服务器太忙，请稍后重试.......";
    }

//    全局降级方法
    public String allMethodFallback(){
        return "服务器太太太太太太忙，请稍后重试.......";
    }


}
